package com.wits.qso.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springside.modules.web.Servlets;

import com.wits.platform.common.constants.ViewType;
import com.wits.platform.common.constants.WebConstants;
import com.wits.platform.common.utils.FileUtil;
import com.wits.platform.common.utils.PageUtil;
import com.wits.platform.common.utils.StringUtil;
import com.wits.platform.web.controller.BaseController;
import com.wits.platform.web.mvc.PageParam;
import com.wits.qso.entity.Vm;
import com.wits.qso.service.VmService;

@Controller
@RequestMapping(value = "qso/vm")
public class VmController extends BaseController
{
	private static final String ATTRIBUTE_VM_BATCH_FILE = "vmBatchFile";
	protected static final Logger logger = LoggerFactory.getLogger( VmController.class );
	@Autowired
	private VmService vmService = null;
	
	@RequestMapping(value = "/toList")
	public String toList() {
		return "qso/vm/list";
	}

	@RequestMapping(value = "/list")
	@ResponseBody
	public String list(Model model, @ModelAttribute("page") PageParam page, HttpServletRequest request) {
		Map<String, Object> searchParams = Servlets.getParametersStartingWith( request, "search_" );

		Page<Vm> listPage = vmService.findPage( Vm.class, searchParams, page );

		model.addAttribute( "searchParams", Servlets.encodeParameterStringWithPrefix( searchParams, "search_" ) );

		return PageUtil.toAjaxPageResult( listPage.getTotalElements(), listPage.getContent() );
	}
	

	@RequestMapping(value = "/view/{viewType}")
	public String toView(Model model, @PathVariable String viewType, @RequestParam String id) {
		if (ViewType.Add.getView().equals( viewType )) {
			model.addAttribute( WebConstants.COMMAND, new Vm() );
			model.addAttribute( "isDisable", "false");
		} else {
			model.addAttribute( WebConstants.COMMAND, vmService.getOne( id ) );
			model.addAttribute( "isDisable", "true");
		}
		
		model.addAttribute( "viewType", viewType );

		return "qso/vm/form";
	}
	
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public Object save(Model model, @ModelAttribute("command") @Valid Vm command, BindingResult result,
			@RequestParam(value = "viewType") String viewType) {
		if (result.hasErrors()) {
			model.addAttribute( WebConstants.COMMAND, command );
			return toView( model, viewType, command.getId() );
		}
		
		if (ViewType.Add.getView().equals( viewType )) {
			command.setDateCre( new Date() );
			command.setUserCre( getCurrentUserId() );
		} else {
			command.setDateUpd( new Date() );
			command.setUserUpd( getCurrentUserId() );
		}
		
		if (vmService.hasVmByIp( command.getIp() )) {
			return ajaxDoneError( "已經存在相同IP" );
		}

		try {
			vmService.save( command );
			return ajaxDoneSuccess( this.getText( "save.success" ) );
		} catch (Exception e) {
			return ajaxDoneError( this.getText( "save.failed" ), e );
		}
	}

	@RequestMapping(value = "/delete")
	@ResponseBody
	public Object delete(String ids) {
		boolean hasSusscesed = false;
		boolean hasErrored = false;
		
		for(String id : Arrays.asList( StringUtil.split( ids, "," ) )) {
			try {
				vmService.delete( id );
				hasSusscesed = true;
			} catch (Exception e) {
				hasErrored = true;
			}
		}
		
		if (hasSusscesed) {
			if (hasErrored) {
				return ajaxDoneError( "有些被引用的虚机无法删除" );
			} else {
				return ajaxDoneSuccess(this.getText("delete.success"));
			}
		} else {
			return ajaxDoneError( "所选虚机已经被引用，无法删除" );
		}
	}
	
	@RequestMapping(value = "/import")
	public String importData(Model model) {
		return "qso/vm/import";
	}
	
	@RequestMapping(value = "/import/save", method = { RequestMethod.POST })
	@ResponseBody
	public Object importData(Model model, HttpSession session) {
		int result = 0;
		String uploadFile = (String) session.getAttribute( ATTRIBUTE_VM_BATCH_FILE );
		try {
			if (null != uploadFile) {
				result = vmService.batchVmData( new HSSFWorkbook( new FileInputStream( new File( session.getServletContext().getRealPath( "/" ) + uploadFile ) ) ), getCurrentUserId() );
				logger.info(" success : {}", result);
			}
			return ajaxDoneSuccess( this.getText( "save.success" ) );
		} catch (Throwable cause) {
			logger.info( cause.getMessage(), cause );
			return ajaxDoneError( this.getText( "save.failed" ) );
		}
	}
	
	@RequestMapping(value = "/import/upload")
	public void importDataUpload(@RequestParam(value = "attachment") MultipartFile multipartFile, HttpSession session) {
		String extension = FilenameUtils.getExtension( multipartFile.getOriginalFilename() );
		String uuid = UUID.randomUUID().toString().replace( "-", "" );
		String storagePath = WebConstants.UPLOAD_DIR + File.separator + "import" + File.separator + uuid;
		try {
			FileUtil.upload( multipartFile, session.getServletContext().getRealPath( "/" ) + storagePath, uuid + "." + extension );
			session.setAttribute( ATTRIBUTE_VM_BATCH_FILE, storagePath + File.separator + uuid + "." + extension );
		} catch (Throwable cause) {
			logger.error( cause.getMessage(), cause );
		}
	}
}
